'use client';

import WebrtcNav from '@/components/WebrtcNav';
import { useEffect } from 'react';

const AudioPage = () => {
	useEffect(() => {
		const canvas = document.getElementById('canvas') as HTMLCanvasElement;
		const ctx = canvas.getContext('2d')!;
		const playBtn = document.getElementById('playBtn')!;

		let audioContext: AudioContext | null = null;
		let oscillator: OscillatorNode | null = null;
		let analyser: AnalyserNode | null = null; // Fix: change type to AnalyserNode
		let animationId: number | null = null;

		// Clear canvas
		function clear() {
			ctx.fillStyle = 'black';
			ctx.fillRect(0, 0, canvas.width, canvas.height);
		}

		// Draw waveform
		function drawWaveform() {
			clear();

			const bufferLength = analyser!.frequencyBinCount;
			const dataArray = new Uint8Array(bufferLength);

			analyser!.getByteTimeDomainData(dataArray);

			ctx.lineWidth = 2;
			ctx.strokeStyle = 'lime';
			ctx.beginPath();

			const sliceWidth = canvas.width / bufferLength;
			let x = 0;

			for (let i = 0; i < bufferLength; i++) {
				const v = dataArray[i] / 128.0;
				const y = (v * canvas.height) / 2;

				if (i === 0) {
					ctx.moveTo(x, y);
				} else {
					ctx.lineTo(x, y);
				}

				x += sliceWidth;
			}

			ctx.lineTo(canvas.width, canvas.height / 2);
			ctx.stroke();
		}

		async function startOscillator() {
			if (!audioContext) {
				audioContext = new window.AudioContext();
			}

			if (audioContext.state === 'suspended') {
				await audioContext.resume();
			}

			oscillator = audioContext.createOscillator();
			oscillator.type = 'sine';
			oscillator.frequency.setValueAtTime(440, audioContext.currentTime);

			analyser = audioContext.createAnalyser(); // Now correctly typed
			analyser.fftSize = 2048;

			oscillator.connect(analyser);
			analyser.connect(audioContext.destination);

			oscillator.start();

			function update() {
				drawWaveform();
				animationId = requestAnimationFrame(update);
			}
			update();

			playBtn.textContent = '停止';
			playBtn.onclick = stopOscillator;
		}

		function stopOscillator() {
			if (oscillator) {
				oscillator.stop();
				oscillator = null;
			}
			if (audioContext) {
				audioContext.close().then(() => {
					audioContext = null;
				});
			}
			if (animationId) {
				cancelAnimationFrame(animationId);
				animationId = null;
			}
			clear();
			playBtn.textContent = '播放正弦波';
			playBtn.onclick = startOscillator;
		}

		playBtn.addEventListener('click', () => {
			if (playBtn.textContent === '播放正弦波') {
				startOscillator();
			} else {
				stopOscillator();
			}
		});

		clear();
	}, []);

	return (
		<div>
			<WebrtcNav text={'audio'}></WebrtcNav>
			<canvas id="canvas" width="600" height="400"></canvas>
			<button id="playBtn" className='rounded px-4 py-2 bg-blue-500 text-white hover:bg-blue-600'>播放正弦波</button>
		</div>
	);
};

export default AudioPage;
